from django.shortcuts import render
from rest_framework.views import APIView
import hashlib, time
import logging
import  json
logger = logging.getLogger('log')
from django.http import JsonResponse
from myblog.models import *


def md5(username):
    now = str(time.time())
    # 利用用户名和

    md5_obj = hashlib.md5(bytes(username + 'mamahaotest', encoding='utf8'))
    md5_obj.update(bytes(now, encoding='utf8'))
    return md5_obj.hexdigest()


class AuthView(APIView):
    '''
    用户登录接口
    '''
    #
    authentication_classes = []

    def post(self, request):

        '''
        :param request:
        :return:
        '''
        data = { }
        data["data"] = {}
        try:
            json_data= eval(json.loads(request.body)["data"])
            username=json_data["username"]
            password = hashlib.md5(bytes(json_data["password"] + 'mamahaotest', encoding='utf8')).hexdigest()
            results = MamahaoUser.objects.filter(user_name=username, user_password=password)
            if results:
                token = md5(username)
                MamahaoUser.objects.update_or_create(user_id=results.values('user_id')[0]['user_id'], defaults={'token': token})
                data["data"]['token'] = token
                data["data"]["uuid"] = results.values("user_id")[0]["user_id"]
                data["data"]["uname"] = results.values("user_account")[0]["user_account"]
                data["data"]["type"] =results.values("user_type")[0]["user_type"]
                data['status'] = "Success"
                data['message'] = '登录成功'
                data['code'] = 200
            else:
                data['error'] = 1
                data['status'] = "Success"
                data['message'] = '用户名或者密码错误'
                data['code'] = 201
        except EOFError as e:
            logging.error(e)
            data['error'] = 1
            data['status'] = "fail"
            data['message'] = '异常'
            data['code'] = 500
        return JsonResponse(data)
